package developer.zyk.ability.chat.ability.memory;

import developer.zyk.ability.chat.dao.entity.ChatHistoryDetailDO;
import developer.zyk.ability.chat.ability.memory.msgHandler.MessageAdapter;
import developer.zyk.ability.chat.service.ChatHistoryService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;

/**
 * @author zhangyongkang
 * @time 2025/5/12 16:16
 * @description
 */
@Component
public class DbChatMemory implements ChatMemory {
    @Resource
    private ChatHistoryService chatHistoryService;
    @Resource
    private MessageAdapter messageAdapter;

    @Override
    public void add(String conversationId, List<Message> messages) {
        Long chatId = Long.valueOf(conversationId);
        messages.forEach(action -> {
            messageAdapter.handleAddMsg(action.getMessageType().getValue(), chatId, action);
        });
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        List<Message> history = chatHistoryService.findChatDetailByChatId(Long.valueOf(conversationId))
                .stream()
                .sorted(Comparator.comparing(ChatHistoryDetailDO::getChatOrder))
                .map(a -> messageAdapter.detail2Message(a))
                .toList();
        int size = history.size();
        if (history.size() <= lastN) {
            return history;
        }
        return history.subList(size - lastN, size);
    }

    @Override
    public void clear(String conversationId) {
        //do nothing
    }

}
